package com.ygswglxt.user.controller;

import com.ygswglxt.common.Result;
import com.ygswglxt.user.entity.User;
import com.ygswglxt.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        String username = request.getHeader("username");
        String role = request.getHeader("role");
        
        Map<String, Object> data = new HashMap<>();
        data.put("userId", userId);
        data.put("username", username);
        data.put("role", role);
        
        return Result.success(data);
    }
    
    // 获取当前用户的详细信息
    @GetMapping("/profile")
    public Result<User> getCurrentUserProfile(HttpServletRequest request) {
        try {
            String userIdStr = request.getHeader("userId");
            if (userIdStr == null || userIdStr.isEmpty()) {
                return Result.error(401, "用户未登录");
            }
            Long userId = Long.parseLong(userIdStr);
            return userService.getUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
    
    // 更新当前用户信息（不能修改名称）
    @PutMapping("/profile")
    public Result<String> updateCurrentUserProfile(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String userIdStr = request.getHeader("userId");
            if (userIdStr == null || userIdStr.isEmpty()) {
                return Result.error(401, "用户未登录");
            }
            Long userId = Long.parseLong(userIdStr);
            return userService.updateUserProfile(userId, params);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新用户信息失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/menu")
    public Result<Map<String, Object>> getMenu(HttpServletRequest request) {
        String role = request.getHeader("role");
        
        Map<String, Object> menu = new HashMap<>();
        
        // 根据角色返回不同的菜单（按照文档要求）
        switch (role) {
            case "EMPLOYEE":
                // 员工：打卡签到、请假申请、调休申请、薪资查询、假期余额
                menu.put("menu", new Object[]{
                    createMenuItem("打卡签到", "/attendance"),
                    createMenuItem("请假申请", "/leave"),
                    createMenuItem("调休申请", "/leave/adjustment"),
                    createMenuItem("薪资查询", "/salary"),
                    createMenuItem("假期余额", "/leave/balance")
                });
                break;
            case "MANAGER":
                // 经理：审批中心、团队考勤、团队薪资、考勤异常管理、数据可视化
                menu.put("menu", new Object[]{
                    createMenuItem("审批中心", "/approval"),
                    createMenuItem("团队考勤", "/attendance/subordinate"),
                    createMenuItem("团队薪资", "/salary/team"),
                    createMenuItem("考勤异常管理", "/attendance/exception"),
                    createMenuItem("数据可视化", "/dashboard")
                });
                break;
            case "HR":
                // HR：员工管理、薪资管理、考勤统计、考勤异常管理、假期余额管理、数据可视化
                menu.put("menu", new Object[]{
                    createMenuItem("员工管理", "/user"),
                    createMenuItem("薪资管理", "/salary"),
                    createMenuItem("考勤统计", "/attendance/statistics"),
                    createMenuItem("考勤异常管理", "/attendance/exception"),
                    createMenuItem("假期余额管理", "/leave/balance"),
                    createMenuItem("数据可视化", "/dashboard")
                });
                break;
            default:
                menu.put("menu", new Object[]{
                    createMenuItem("系统设置", "/settings")
                });
        }
        
        return Result.success(menu);
    }
    
    // 获取所有用户列表（HR使用）
    @GetMapping("/list")
    public Result<List<User>> getUserList(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (role == null || !"HR".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        try {
            return userService.getAllUsers();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户列表失败: " + e.getMessage());
        }
    }
    
    // 获取所有经理ID（内部服务调用，不需要权限验证）
    @GetMapping("/managers")
    public Result<List<Map<String, Object>>> getManagers() {
        try {
            List<User> users = userService.getAllUsers().getData();
            List<Map<String, Object>> managers = new ArrayList<>();
            for (User user : users) {
                if ("MANAGER".equals(user.getRole())) {
                    Map<String, Object> manager = new HashMap<>();
                    manager.put("id", user.getId());
                    manager.put("name", user.getName());
                    manager.put("username", user.getUsername());
                    managers.add(manager);
                }
            }
            return Result.success(managers);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取经理列表失败: " + e.getMessage());
        }
    }
    
    // 获取系统配置
    @GetMapping("/config")
    public Result<Map<String, Object>> getSystemConfig(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (role == null || !"OTHER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return userService.getSystemConfig();
    }
    
    // 更新系统配置
    @PutMapping("/config")
    public Result<String> updateSystemConfig(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        String role = request.getHeader("role");
        if (role == null || !"OTHER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return userService.updateSystemConfig(params);
    }
    
    private Map<String, String> createMenuItem(String name, String path) {
        Map<String, String> item = new HashMap<>();
        item.put("name", name);
        item.put("path", path);
        return item;
    }
}

